package com.usian.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.usian.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private FastFileStorageClient storageClient;

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {

        String filename = file.getOriginalFilename();

        String contentType = file.getContentType();
        List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif");
        //1、校验类型
        if(!CONTENT_TYPES.contains(contentType)){
            return Result.error("文件类型不合法："+filename);
        }

        //2、校验内容
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if(bufferedImage == null){
            return Result.error("文件内容不合法："+filename);
        }

        //3、上传
        String extName = filename.substring(filename.indexOf("."));
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);

        //4、返回图片路径
        return Result.ok("http://image.usian.com/"+storePath.getFullPath());
    }
}
